package com.oem.upgrade;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class MainActivity extends AppCompatActivity {

    private boolean mReceiveThreadRunning = true;
    private boolean mReceiveThreadRunning2 = true;
    private static DatagramSocket socket;
    private static DatagramSocket cmdSocket;
    private static final int RECEIVEPORT = 10001;
    private static final int CMDPORT = 10002;
    private static final int SENDPORT = 10000;
    private byte[] mReceive = new byte[32];
    private byte[] mReceive2 = new byte[32];

    private static final String SERVERADDRESS = "127.0.0.1";
    private int mCommandGuardInerval = 50; //ms
    private static final String TAG = "UPGRADE_CHUNK";
    private static final int REQUEST_PERMISSION_CODE = 100;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_PERMISSION_CODE);
        } else {
            // 权限已授权，读取文件
            readImageFile();
        }

        TextView text = (TextView) findViewById(R.id.show_text_view);
        UpgradeAPI upgradeAPI = new UpgradeAPI();

        // 启动接收线程
        try {
            socket = new DatagramSocket(RECEIVEPORT);
        } catch (SocketException e) {
            e.printStackTrace();
            Log.e(TAG, "Socket 初始化失败");
        }

        byte[][] upgradeChunks = upgradeAPI.getUpgradeChunks();
        Log.d(TAG, "length: " + upgradeChunks.length);



        new Thread(new Runnable() {
            @Override
            public void run() {
                final DatagramPacket dPacket = new DatagramPacket(mReceive, mReceive.length);
                while (mReceiveThreadRunning) {
                    try {
                        // 接收数据
                        socket.receive(dPacket);
                        int receiveSize = dPacket.getLength();
                        String command = bytesToHex(mReceive, receiveSize);
                        Log.d(TAG, "收到命令: " + command);
                    } catch (IOException e) {
                        Log.e(TAG, "接收数据时出错");
                        e.printStackTrace();
                    }
                    Log.d(TAG, "\n");
                }
            }
        }).start();


        printChunksAsHex(upgradeChunks);

        for (byte[] chunk : upgradeChunks) {
            sendCommand(chunk); // 发送命令

            try {
                Thread.sleep(5000); // 等待1秒（1000毫秒）
            } catch (InterruptedException e) {
                e.printStackTrace(); // 处理中断异常
            }
        }


    }

    // 处理权限申请结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                readImageFile();
            } else {
                Toast.makeText(this, "权限被拒绝，无法读取文件", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 读取 /sdcard/Download/AvironUCB_V2.img 文件
    private void readImageFile() {
        try {
            // 获取外部存储路径
            File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File imgFile = new File(downloadDir, "AvironUCB_V2.img");

            // 检查文件是否存在
            if (!imgFile.exists()) {
                Log.e(TAG, "文件不存在: " + imgFile.getAbsolutePath());
                Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
                return;
            }

            Log.i(TAG, "读取文件: " + imgFile.getAbsolutePath());

            // 读取文件内容
            FileInputStream fis = new FileInputStream(imgFile);
            BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
            StringBuilder content = new StringBuilder();
            String line;

            // 逐行读取
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }

            reader.close();
            fis.close();

            // 打印文件内容
            Log.i(TAG, "文件内容大小: " + content.toString().length());
            Toast.makeText(this, "文件读取成功", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            Log.e(TAG, "读取文件失败: " + e.getMessage());
            Toast.makeText(this, "读取文件失败", Toast.LENGTH_SHORT).show();
        }
    }

    public static void printChunksAsHex(byte[][] chunks) {
        for (int i = 0; i < chunks.length; i++) {
            StringBuilder hexBuilder = new StringBuilder();
            for (byte b : chunks[i]) {
                hexBuilder.append(String.format("%02X ", b));
            }
            Log.d(TAG, "Chunk " + i + ": " + hexBuilder.toString().trim());
        }
    }

    private void sendCommand(final byte[] value) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 初始化socket
                DatagramSocket socket = null;
                try {
                    socket = new DatagramSocket();
                } catch (SocketException e) {
                    e.printStackTrace();
                }

                InetAddress serverAddress = null;
                try {
                    serverAddress = InetAddress.getByName(SERVERADDRESS);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }

                // 创建一个包含命令数据、服务器地址和端口号的数据包
                DatagramPacket packet = new DatagramPacket(value, value.length, serverAddress, SENDPORT);
                try {
                    // 将UDP数据包发送到中间件
                    socket.send(packet);
                    Log.d(TAG, "send success!");
                    Log.d(TAG, "packet length: " + packet.getLength());
                } catch (IOException e) {
                    Log.d(TAG, "send failed!");
                    e.printStackTrace();
                }
                socket.close();

                // 等待指定的命令保护间隔，以免发送过多命令
                try {
                    Thread.sleep(mCommandGuardInerval);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static String bytesToHex(byte[] bytes, int len) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            sb.append(String.format("%02X", bytes[i]));
        }
        return sb.toString().trim();
    }

    // 将十六进制字符串转换为字节数组
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }
}
